package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 套餐业务实现
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.保存套餐基本信息
        setmealDao.add(setmeal);
        //2.保存套餐与检查组关联信息
        setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
        //将保存成功的图片名称到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_IMG_DB,setmeal.getImg());
    }

   //保存检查项与套餐的关联信息
    private void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds) {
        if(checkgroupIds==null||checkgroupIds.length==0){
            return;
        }

        for (Integer id:checkgroupIds) {
            Map<String,Integer>  map = new HashMap<>();
            map.put("setmeal_id",setmealId);
            map.put("checkgroup_id",id);

            setmealDao.setSetmealAndCheckgroup(map);
        }
    }

    //分页
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);

        Page page = (Page)setmealDao.queryByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }


    //根据id查询套餐信息
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    //查询套餐与检查组的关联关系
    @Override
    public List<Integer> findCheckgroupIds(Integer id) {
       return setmealDao.findCheckgroupIds(id);
    }

    //点击编辑确认
    //TODO
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //更新套餐信息
        setmealDao.edit(setmeal);
        //删除中间表t_setmeal_checkgroup关联
        setmealDao.deleteAssocation(setmeal.getId());
        //设置套餐与检查组之间的关联信息
        setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
    }


    //删除套餐
    @Override
    public void deleteById(Integer id) {
        //删除中间表关联数据
        setmealDao.deleteAssocation(id);
        //删除套餐
        setmealDao.deleteById(id);
    }


    //查询所有套餐（预约）
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //根据套餐id查询套餐信息
    @Override
    public Setmeal findBySetmealId(Integer id) {
       return setmealDao.findBySetmealId(id);
    }
}